import express from "express";
import MySQLPool from '../mysqlCreatePool';
import { upload } from "../uploadFile";
import { host } from "../server.config";
const router = express.Router();
const db = new MySQLPool();
// 获取奖品
router.get("/", async (req: any, res: any) => {
    try {
        const { id } = req.auth
        const sql = `SELECT t.id,t.bonus_id,t.status,t.time,t.num,b.name,(t.num*b.num) as sum,t.img FROM todo AS t LEFT JOIN bonus AS b ON t.bonus_id=b.id WHERE t.user_id=${id}`;
        const [sqlres] = await db.queryRows(sql);
        res.send({
            code: 200,
            message: '',
            data: sqlres,
        });
    } catch (e) {
        res.send({
            code: 201,
            message: e,
            data: null,
        });
    }
});
// 编辑奖品
router.post("/update", upload.array('img'), async (req: any, res: any) => {
    try {
        const { id } = req.auth
        const todo = { ...req.body }
        const fls = req.files
        if ([1, 4, 5].includes(Number(todo.bid)) && fls.length === 0) {
            res.send({
                code: 201,
                message: '事件类型需要上传图片',
                data: null,
            });
            return
        }
        // let sql = ''
        // if (!todo.id) {
        //     const img = ''
        //     sql = `INSERT INTO todo (bonus_id,num,user_id,status,img,time) VALUES (${todo.bid}, ${todo.num}, ${id}, 1, '${img}',CONVERT(NOW(), CHAR));`
        // }
        // else {
        //     sql = 'update reward set '
        //     if (req.file && !todo.img?.includes(host)) {
        //         todo.img = req.file?.filename ? '/uploads/' + req.file?.filename : null
        //         sql += `img='${todo.img}',`
        //     }
        //     sql += `name='${todo.name}',num=${todo.num},chang_time=CONVERT(NOW(), CHAR) where id=${todo.id}`;
        // }
        // console.log(sql)

        if (req.files) {
            console.log(req.files)
        }
        // const sql = `SELECT t.id,t.bonus_id,t.status,t.time,t.num,b.name,(t.num*b.num) as sum FROM todo AS t LEFT JOIN bonus AS b ON t.bonus_id=b.id WHERE t.user_id=${id}`;
        // const [sqlres] = await db.queryRows(sql);
        res.send({
            code: 200,
            message: '',
            data: req.body,
        });
    } catch (e) {
        res.send({
            code: 201,
            message: e,
            data: null,
        });
    }
});
export default router